{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello! How can I assist you today? 😊\n"
     ]
    }
   ],
   "source": [
    "# Please install OpenAI SDK first: `pip3 install openai`\n",
    "\n",
    "import os\n",
    "from openai import OpenAI\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv())\n",
    "API_KEY = os.environ['OPENAI_API_KEY']\n",
    "client = OpenAI(api_key=API_KEY, base_url=\"https://api.deepseek.com\")\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "    model=\"deepseek-chat\",\n",
    "    messages=[\n",
    "        {\"role\": \"system\", \"content\": \"You are a helpful assistant\"},\n",
    "        {\"role\": \"user\", \"content\": \"Hello\"},\n",
    "    ],\n",
    "    stream=False\n",
    ")\n",
    "\n",
    "print(response.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ChatCompletion(id='8fad125e-679f-4071-a031-b15f3af38488', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='Hello! How can I assist you today? 😊', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=None))], created=1741782783, model='deepseek-chat', object='chat.completion', service_tier=None, system_fingerprint='fp_3a5770e1b4_prod0225', usage=CompletionUsage(completion_tokens=11, prompt_tokens=9, total_tokens=20, completion_tokens_details=None, prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0), prompt_cache_hit_tokens=0, prompt_cache_miss_tokens=9))\n",
      "['__abstractmethods__', '__annotations__', '__class__', '__class_getitem__', '__class_vars__', '__copy__', '__deepcopy__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__fields__', '__fields_set__', '__format__', '__ge__', '__get_pydantic_core_schema__', '__get_pydantic_json_schema__', '__getattr__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__pretty__', '__private_attributes__', '__pydantic_complete__', '__pydantic_computed_fields__', '__pydantic_core_schema__', '__pydantic_custom_init__', '__pydantic_decorators__', '__pydantic_extra__', '__pydantic_fields__', '__pydantic_fields_set__', '__pydantic_generic_metadata__', '__pydantic_init_subclass__', '__pydantic_parent_namespace__', '__pydantic_post_init__', '__pydantic_private__', '__pydantic_root_model__', '__pydantic_serializer__', '__pydantic_validator__', '__reduce__', '__reduce_ex__', '__replace__', '__repr__', '__repr_args__', '__repr_name__', '__repr_recursion__', '__repr_str__', '__rich_repr__', '__setattr__', '__setstate__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', '_calculate_keys', '_check_frozen', '_copy_and_set_values', '_get_value', '_iter', 'completion_tokens', 'completion_tokens_details', 'construct', 'copy', 'dict', 'from_orm', 'json', 'model_computed_fields', 'model_config', 'model_construct', 'model_copy', 'model_dump', 'model_dump_json', 'model_extra', 'model_fields', 'model_fields_set', 'model_json_schema', 'model_parametrized_name', 'model_post_init', 'model_rebuild', 'model_validate', 'model_validate_json', 'model_validate_strings', 'parse_file', 'parse_obj', 'parse_raw', 'prompt_tokens', 'prompt_tokens_details', 'schema', 'schema_json', 'to_dict', 'to_json', 'total_tokens', 'update_forward_refs', 'validate']\n"
     ]
    }
   ],
   "source": [
    "print(response)\n",
    "print(dir(response.usage))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "CLIENT = OpenAI(api_key=API_KEY, base_url=\"https://api.deepseek.com\")\n",
    "def get_completion(prompt, model=\"deepseek-chat\"):\n",
    "\n",
    "    messages=[\n",
    "        {\"role\": \"system\", \"content\": \"You are a helpful assistant\"},\n",
    "        {\"role\": \"user\", \"content\": prompt}\n",
    "    ]\n",
    "    response = CLIENT.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        stream=False\n",
    "    )\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The capital of China is Beijing. It is one of the most populous cities in the world and serves as the political, cultural, and educational center of the country. Beijing is home to many historical landmarks, such as the Forbidden City, the Great Wall of China, and Tiananmen Square.\n"
     ]
    }
   ],
   "source": [
    "response = get_completion(\"What is the captial of China\")\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "昆山市位于中国江苏省东南部，与上海市接壤。昆山市与上海青浦区的距离大约在**30公里至50公里**之间，具体距离取决于你从昆山市的哪个位置出发以及到达青浦区的具体地点。\n",
      "\n",
      "- 如果你从昆山市中心（如昆山市政府）出发，到青浦区中心（如青浦区政府）的直线距离大约在**40公里左右**。\n",
      "- 如果通过高速公路（如G2京沪高速或G1501上海绕城高速）驾车前往，实际行驶距离可能会稍长一些，通常在**50公里左右**，车程大约需要**1小时**，具体时间取决于交通状况。\n",
      "\n",
      "总的来说，昆山市与上海青浦区的距离较近，交通便利，两地之间的往来非常频繁。\n"
     ]
    }
   ],
   "source": [
    "response = get_completion(\"告诉我，昆山市距离上海青浦距离范围？\")\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_completion_from_messages(messages, model=\"deepseek-chat\", temperature=1.0):\n",
    "    response = CLIENT.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=temperature,\n",
    "        stream=False\n",
    "    )\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Oh, the dog with a wag in his tail,\n",
      "He zips through the yard like a speedy snail!\n",
      "With a bark and a bounce, he’s a joy to see,\n",
      "A happy, yappy, snappy spree!\n",
      "He chases the sun, he leaps for the sky,\n",
      "With a grin so wide, you can’t help but sigh.\n",
      "Oh, happy dog, you’re a furry delight,\n",
      "A ball of love, from morning to night!\n"
     ]
    }
   ],
   "source": [
    "messages=[\n",
    "    {\"role\": \"system\", \"content\": \"You are a helpful assistant who response in the style of Dr Seuss.\"},\n",
    "    {\"role\": \"user\", \"content\": \"write me a very short poem about a happy dog\"},\n",
    "]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A wagging tail, a joyful bark, the happy dog lights up the park.\n"
     ]
    }
   ],
   "source": [
    "messages=[\n",
    "    {\"role\": \"system\", \"content\": \"All your response is one sentence long.\"},\n",
    "    {\"role\": \"user\", \"content\": \"write me a very short poem about a happy dog\"},\n",
    "]\n",
    "response = get_completion_from_messages(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_completion_and_token_count(messages, model=\"deepseek-chat\", temperature=1.0, max_tokens=1000):\n",
    "    response = CLIENT.chat.completions.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=temperature,\n",
    "        stream=False,\n",
    "        max_tokens=max_tokens\n",
    "    )\n",
    "    \n",
    "    content = response.choices[0].message.content\n",
    "    token_dict = {\n",
    "        'prompt_tokens': response.usage.prompt_tokens,\n",
    "        'completion_tokens': response.usage.completion_tokens,\n",
    "        'total_tokens': response.usage.total_tokens,\n",
    "    }\n",
    "    return content, token_dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A wagging tail, a joyful bark, the happy dog lights up the park.\n"
     ]
    }
   ],
   "source": [
    "messages=[\n",
    "    {\"role\": \"system\", \"content\": \"All your response is one sentence long.\"},\n",
    "    {\"role\": \"user\", \"content\": \"write me a very short poem about a happy dog\"},\n",
    "]\n",
    "response, token_dict = get_completion_and_token_count(messages, temperature=1)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'prompt_tokens': 21, 'completion_tokens': 17, 'total_tokens': 38}\n"
     ]
    }
   ],
   "source": [
    "print(token_dict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## [Classification](https://learn.deeplearning.ai/courses/chatgpt-building-system/lesson/x51uj/classification)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```json\n",
      "{\n",
      "  \"primary\": \"Account Management\",\n",
      "  \"secondary\": \"Close account\"\n",
      "}\n",
      "```\n"
     ]
    }
   ],
   "source": [
    "delimiter = \"####\"\n",
    "system_message = f\"\"\"\n",
    "You will be provided with customer service queries. \\\n",
    "The customer service query will be delimited with \\\n",
    "{delimiter} characters.\n",
    "Classify each query into a primary category \\\n",
    "and a secondary category. \n",
    "Provide your output in json format with the \\\n",
    "keys: primary and secondary.\n",
    "\n",
    "Primary categories: Billing, Technical Support, \\\n",
    "Account Management, or General Inquiry.\n",
    "\n",
    "Billing secondary categories:\n",
    "Unsubscribe or upgrade\n",
    "Add a payment method\n",
    "Explanation for charge\n",
    "Dispute a charge\n",
    "\n",
    "Technical Support secondary categories:\n",
    "General troubleshooting\n",
    "Device compatibility\n",
    "Software updates\n",
    "\n",
    "Account Management secondary categories:\n",
    "Password reset\n",
    "Update personal information\n",
    "Close account\n",
    "Account security\n",
    "\n",
    "General Inquiry secondary categories:\n",
    "Product information\n",
    "Pricing\n",
    "Feedback\n",
    "Speak to a human\n",
    "\n",
    "\"\"\"\n",
    "user_message = f\"\"\"\\\n",
    "I want you to delete my profile and all of my user data\"\"\"\n",
    "messages =  [  \n",
    "{'role':'system', \n",
    " 'content': system_message},    \n",
    "{'role':'user', \n",
    " 'content': f\"{delimiter}{user_message}{delimiter}\"},  \n",
    "] \n",
    "response = get_completion_from_messages(messages)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```json\n",
      "{\n",
      "  \"primary\": \"General Inquiry\",\n",
      "  \"secondary\": \"Product information\"\n",
      "}\n",
      "```\n"
     ]
    }
   ],
   "source": [
    "user_message = f\"\"\"\\\n",
    "Tell me more about your flat screen tvs\"\"\"\n",
    "messages =  [  \n",
    "{'role':'system', \n",
    " 'content': system_message},    \n",
    "{'role':'user', \n",
    " 'content': f\"{delimiter}{user_message}{delimiter}\"},  \n",
    "] \n",
    "response = get_completion_from_messages(messages)\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## [Moderation](https://learn.deeplearning.ai/courses/chatgpt-building-system/lesson/w7r01/moderation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from openai import Moderation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = Moderation.create(\n",
    "        input=\"\"\"\n",
    "Here's the plan.  We get the warhead, \n",
    "and we hold the world ransom...\n",
    "...FOR ONE MILLION DOLLARS!\n",
    "\"\"\"\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
